import java.io.*;
import java.net.*;
import java.util.*;

public class Server {
    private static final int PORT = 12345;
    // 用于保存所有客户端处理线程
    private static Set<ClientHandler> clientHandlers = Collections.synchronizedSet(new HashSet<>());

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("服务器已启动，等待客户端连接...");

        while (true) {
            Socket clientSocket = serverSocket.accept();
            ClientHandler handler = new ClientHandler(clientSocket);
            clientHandlers.add(handler);
            handler.start();
        }
    }

    // 服务器广播消息给所有客户端
    static void broadcast(String message, ClientHandler sender) {
        synchronized (clientHandlers) {
            for (ClientHandler client : clientHandlers) {
                if (client != sender) {
                    client.sendMessage(message);
                }
            }
        }
    }

    // 移除断开连接的客户端
    static void removeClient(ClientHandler client) {
        clientHandlers.remove(client);
    }

    // 内部类：处理每个客户端连接
    static class ClientHandler extends Thread {
        private Socket socket;
        private PrintWriter out;
        private BufferedReader in;
        private String name;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                out.println("请输入你的名字：");
                name = in.readLine();
                System.out.println(name + " 已连接：" + socket.getRemoteSocketAddress());

                broadcast("【系统消息】" + name + " 加入了聊天室", this);

                String message;
                while ((message = in.readLine()) != null) {
                    if ("bye".equalsIgnoreCase(message)) {
                        break;
                    }
                    System.out.println("收到消息：" + name + ": " + message);
                    broadcast(name + ": " + message, this);
                }
            } catch (IOException e) {
                System.out.println("连接异常：" + e.getMessage());
            } finally {
                try {
                    socket.close();
                } catch (IOException ignored) {}
                broadcast("【系统消息】" + name + " 离开了聊天室", this);
                removeClient(this);
                System.out.println(name + " 已断开连接");
            }
        }

        public void sendMessage(String message) {
            out.println(message);
        }
    }
}
